package frapell.funny.quotes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


public class BashorgReader extends Activity {
	
	boolean updating = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    	
        setContentView(R.layout.main);
        if (savedInstanceState == null){
        	new updateQuotes().execute();
        }
        
        loadQuote();
        
    }
        
    private class updateQuotes extends AsyncTask<Void, Integer, Void> {
    	
		@Override
		protected Void doInBackground(Void... params) {
			updating = true;
			
    		publishProgress(0);
    		String random_page = null;
    		boolean error = false;
    		
			try {
				random_page = getRandomQuotes();
			} catch (IOException e) {
				error = true;
			}
    		
    		if (!error){
				publishProgress(1);
	    		
	    		createQuotes(random_page);
	

				publishProgress(2);
    		}
    		else{
				publishProgress(-1);
    		}
			return null;

        }
        
        protected void onProgressUpdate(Integer... progress) {

        	if (progress[0] == -1){
            	showMsg(getString(R.string.error));		
            	updating=false;
        	}
        	
        	if (progress[0] == 0){
            	showMsg(getString(R.string.getting_data));	
        	}
        	if (progress[0] == 1){
            	showMsg(getString(R.string.loading_quotes));	
        	}
        	
        	if (progress[0] == 2){
            	showMsg(getString(R.string.done));	
            	updating=false;
            	loadQuote();
        	}
        }

        protected void onPostExecute(Void none) {
//        	try {
//				this.finalize();
//			} catch (Throwable e) {
//				e.printStackTrace();
//			}
        }
        
    }

    private void createQuotes(String random_page){
    	//Had to write this awful parser manually
    	String tag = "";
    	boolean have_qn_open_tag = false;
    	boolean have_b_open_tag = false;
    	boolean have_q_open_tag = false;
    	
    	String quote_number = "";
    	String quote = "";
        char ch;
        
        BashOrgQuotes quotes = BashOrgQuotes.getInstance();
        

    	
    	for (int i=0; i< random_page.length(); i++) {
			
    		ch = random_page.charAt(i); 
    		    		
			if ( ch == '<' && tag == ""){
    			tag = tag + random_page.charAt(i);
    		}
    		
			else if (ch == '>' && tag != ""){
    			tag = tag + ch;
    			if (tag.equals("<p class=\"quote\">")){
        			have_qn_open_tag = true;
    			}
    			else if (have_qn_open_tag && tag.equals("<b>")){
    				have_b_open_tag = true;    				
    			}
    			else if (tag.equals("<p class=\"qt\">")){
    				have_q_open_tag = true;    				
    			}
    			
    			else if (tag.equals("</p>") && 
    					 have_q_open_tag){
    				have_q_open_tag = false;

					//At this point we should have the quote number and content
    				quotes.storeTitle(quote_number);
    				quotes.storeQuote(quote);
    		    	quote_number = "";
    		    	quote = "";
    		    	
    			}
    			else if (tag.equals("</p>") && 
       					 have_qn_open_tag){
       				have_qn_open_tag = false;
    			}
    			else if (tag.equals("</b>") && 
       					 have_b_open_tag){
       				have_b_open_tag = false;
       			}       			
    		
    			else if (have_q_open_tag){
    				quote = quote + tag;
    			}
    			tag = "";
    		}

			else if (tag != ""){
    			tag = tag + ch;
    		}
    			
			else if (have_b_open_tag && have_qn_open_tag){
				quote_number = quote_number + ch;
			}
    		
			else if (have_q_open_tag){
				quote = quote + ch;
			}
			
		}
    	
	}
    		
    
    
    private String getRandomQuotes() throws IOException {
    	URL bashorg = null;
		try {
			bashorg = new URL("http://bash.org/?random");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
    	BufferedReader in = null;
		
		in = new BufferedReader(
								new InputStreamReader(
								bashorg.openStream()));
	

    	String aux_text = "";
    	String returned_value = "";

    	try {
			while ((aux_text = in.readLine()) != null)
			    returned_value = returned_value.concat(aux_text);
		} catch (IOException e) {
			e.printStackTrace();
		}
    	

    	try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return returned_value;
    }
    

    public void nextQuote(View view) {

        BashOrgQuotes quotes = BashOrgQuotes.getInstance();
        
        quotes.nextQuote();
        
    	loadQuote();
    	
    	if (quotes.shouldUpdate()){	    		
	        if (!updating) {
				new updateQuotes().execute();
	        }
    	}	
    }


    public void prevQuote(View view) {

        BashOrgQuotes quotes = BashOrgQuotes.getInstance();
        
        quotes.previousQuote();

		loadQuote();
    	
    }


	private void loadQuote() {

        BashOrgQuotes quotes = BashOrgQuotes.getInstance();
        
		String title = quotes.getCurrentTitle();
    	Spanned quote = Html.fromHtml(quotes.getCurrentQuote());
    	
      	TextView titletext = (TextView) findViewById(R.id.titleHolder);
      	TextView quotetext = (TextView) findViewById(R.id.textHolder);

      	titletext.setText(title);
      	quotetext.setText(quote.toString());
	}
    
	private void showMsg(String msg) {
		Context context = getApplicationContext();
    	CharSequence text = msg;
    	int duration = Toast.LENGTH_SHORT;

    	Toast toast = Toast.makeText(context, text, duration);
    	toast.show();
	}
	
}